package com.hanxiaozhang.heartbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Random;

/**
 * 〈一句话功能简述〉<br>
 * 〈心跳检测客户端〉
 *
 * @author hanxinghua
 * @create 2022/11/27
 * @since 1.0.0
 */
public class HeartBeatClient {

    private int port;
    private Channel channel;
    private Random random;


    public static void main(String[] args) throws Exception {
        HeartBeatClient client = new HeartBeatClient(8090);
        client.start();
    }


    public HeartBeatClient(int port) {
        this.port = port;
        random = new Random();
    }

    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                                 @Override
                                 protected void initChannel(SocketChannel ch) throws Exception {
                                     ChannelPipeline pipeline = ch.pipeline();
                                     pipeline.addLast("decoder", new StringDecoder());
                                     pipeline.addLast("encoder", new StringEncoder());
                                     // 客户端对心跳检测事件的处理
                                     pipeline.addLast(new HeartBeatClientHandler());
                                 }
                             }
                    );

            channel = bootstrap.connect("localhost", port).sync().channel();
            String text = "I am alive";
            while (channel.isActive()) {
                sendMsg(text);
            }
        } catch (Exception e) {
            // do something
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public void sendMsg(String text) throws Exception {
        int num = random.nextInt(10);
        Thread.sleep(num * 1000);
        channel.writeAndFlush(text);
    }

}

